/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.acts;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.ListIterator;

import com.hiddenequity.conversion_service.ConversionResponseParser;
import com.hiddenequity.conversion_service.ConversionService;
import com.hiddenequity.utils.AuthService;
import com.hiddenequity.utils.ColorPickerDialog;
import com.hiddenequity.utils.Communication;
import com.hiddenequity.utils.DataValidator;
import com.hiddenequity.utils.Language;
import com.hiddenequity.utils.LocationDataProvider;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;


public class Act_ConversionSettings extends Act_Super{

	private Spinner spin_conversion_category;
	private Spinner spin_conversion_page_security;
	private Spinner spin_conversion_markup_language;
	private Spinner spin_conversion_notif_language;
	private EditText edit_conversion_revenue_value;
	private RadioButton rb_conversion_notif_line1;
	private RadioButton rb_conversion_notif_line2;
	private RadioButton rb_conversion_add_notif;
	private RadioButton rb_conversion_no_notif;
	private LinearLayout ll_conversion_notif;
	private View view_pick_color;
	private EditText edit_conversion_notif_bg_color;
	
	private String conversionId;
	private String category;
	private String markupLanguage;
	private String httpProtocol;
	private String textFormat;
	private String conversionPageLanguage;
	private String backgroundColor;
	private String userRevenueValue;
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.super_operation_layout);	
        
		((ViewStub) findViewById(R.id.stub_conversion_settings)).inflate();
        
        title.setText(getString(R.string.title_conversion_edit_settings));
        sub_title.setVisibility(View.GONE);
        filter.setVisibility(View.GONE);
        
        // Get extras
        Intent intent = getIntent();
        conversionId = intent.getStringExtra("conversionId");
        category = intent.getStringExtra("category");
        markupLanguage = intent.getStringExtra("markupLanguage");
        httpProtocol = intent.getStringExtra("httpProtocol");
        textFormat = intent.getStringExtra("textFormat");
        conversionPageLanguage = intent.getStringExtra("conversionPageLanguage");
        backgroundColor = intent.getStringExtra("backgroundColor");
        userRevenueValue = intent.getStringExtra("userRevenueValue");
        
        // Prevent keyboard popping up
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        
        //inflate category
    	spin_conversion_category = (Spinner) findViewById(R.id.spin_conversion_category);
		// set position
		String[] categoryArray =  getResources().getStringArray(R.array.arr_conversionCategory_api);
		ArrayList<String> categoryList = new ArrayList<String>(Arrays.asList(categoryArray));	
		int position = categoryList.indexOf(category);
		inflateSpinner(spin_conversion_category, R.array.arr_conversionCategory_ui, position);
		
    	// inflate page security
    	spin_conversion_page_security = (Spinner) findViewById(R.id.spin_conversion_page_security);
    	// set position 
		String[] pageSecurityArray = getResources().getStringArray(R.array.arr_pageSecurity);
		ArrayList<String> pageSecurityList = new ArrayList<String>(Arrays.asList(pageSecurityArray));	
		position = pageSecurityList.indexOf(httpProtocol);		
    	
		inflateSpinner(spin_conversion_page_security, R.array.arr_pageSecurity, position);
		
		// inflate markup languages
    	spin_conversion_markup_language = (Spinner) findViewById(R.id.spin_conversion_markup_language);
    	// get position
		String[] markupLangueageArray = getResources().getStringArray(R.array.arr_markupLanguage);
		ArrayList<String> markupLangueageList = new ArrayList<String>(Arrays.asList(markupLangueageArray));	
		position = markupLangueageList.indexOf(markupLanguage);
    	
		inflateSpinner(spin_conversion_markup_language, R.array.arr_markupLanguage, position);


		// set revenue value
    	edit_conversion_revenue_value = (EditText) findViewById(R.id.edit_conversion_revenue_value);
    	edit_conversion_revenue_value.setText(userRevenueValue);
	
    	// inflate languages
    	spin_conversion_notif_language = (Spinner) findViewById(R.id.spin_conversion_notif_language);
    	ArrayList<Language> languageList = LocationDataProvider.getLanguageList(getApplication());
    	ArrayAdapter<Language> adapter = new ArrayAdapter<Language>(this,
				android.R.layout.simple_spinner_item,
				languageList);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spin_conversion_notif_language.setAdapter(adapter);
        ListIterator<Language> languageIterator = languageList.listIterator();
		while(languageIterator.hasNext()){
			String langCode = languageIterator.next().getCode();
			if(langCode.equals(conversionPageLanguage)){
				spin_conversion_notif_language.setSelection(languageIterator.nextIndex()-1);
				break;
			}
		} 
		
		// set text format
		rb_conversion_add_notif = (RadioButton) findViewById(R.id.rb_conversion_add_notif);
		rb_conversion_no_notif = (RadioButton) findViewById(R.id.rb_conversion_no_notif);
		
		rb_conversion_notif_line1 = (RadioButton) findViewById(R.id.rb_conversion_notif_line1);
		rb_conversion_notif_line2 = (RadioButton) findViewById(R.id.rb_conversion_notif_line2);		
		ll_conversion_notif = (LinearLayout) findViewById(R.id.ll_conversion_notif);
		if(textFormat.equals("ONE_LINE")){
			rb_conversion_notif_line1.setChecked(true);
		} else if(textFormat.equals("TWO_LINE")){
			rb_conversion_notif_line2.setChecked(true);
		} else if(textFormat.equals("HIDDEN")){
			//Hide linear layout here
			ll_conversion_notif.setVisibility(View.GONE);
		}

		
		// Set bg color
		edit_conversion_notif_bg_color = (EditText) findViewById(R.id.edit_conversion_notif_bg_color);
		edit_conversion_notif_bg_color.setText(backgroundColor.toUpperCase());
		view_pick_color = findViewById(R.id.view_pick_color);
		backgroundColor = "ff" + backgroundColor;
		int color = hex2decimal(backgroundColor);
		view_pick_color.setBackgroundColor(color);
		view_pick_color.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				new ColorPickerDialog(Act_ConversionSettings.this, colorChangedListener, getColor()).show();
			}
		});
		
		
		// Set EditText listener
		final EditText edit_conversion_notif_bg_color = (EditText) findViewById(R.id.edit_conversion_notif_bg_color);
		TextWatcher fieldValidatorTextWatcher = new TextWatcher() {
		        public void onTextChanged(CharSequence s, int start, int before, int count) {
		            if (s.length() == 6) {
						view_pick_color.setBackgroundColor(getColor());
		            }
		        }

				public void afterTextChanged(Editable arg0) {
					// TODO Auto-generated method stub
					
				}

				public void beforeTextChanged(CharSequence arg0, int arg1,
						int arg2, int arg3) {
					// TODO Auto-generated method stub
					
				}

		    };
		    edit_conversion_notif_bg_color.addTextChangedListener(fieldValidatorTextWatcher);
    
    }//onCreate

    
    /*
     * Get color from edittext
     */
    private int getColor(){
		return hex2decimal("FF" + edit_conversion_notif_bg_color.getText().toString());
    }//getColor
    
    
    public static int hex2decimal(String s) {
        String digits = "0123456789ABCDEF";
        s = s.toUpperCase();
        int val = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int d = digits.indexOf(c);
            val = 16*val + d;
        }
        return val;
    }
    
    
    /*
     * Color change listener
     */
	private ColorPickerDialog.OnColorChangedListener colorChangedListener = new ColorPickerDialog.OnColorChangedListener() {
		public void colorChanged(int color) {
			view_pick_color.setBackgroundColor(color);
			String hexColor = Integer.toHexString(color);
			hexColor = (String) hexColor.subSequence(2, hexColor.length());
			edit_conversion_notif_bg_color.setText(hexColor.toUpperCase());
		}
	};//DialogClickListener
    
	
	
    /*
     * Form logic
     */
    public void setFormLogic(View v){
    	switch (v.getId()) {
		case R.id.rb_conversion_add_notif:
			ll_conversion_notif.setVisibility(View.VISIBLE);
			break;
		case R.id.rb_conversion_no_notif:
			ll_conversion_notif.setVisibility(View.GONE);
			break;
    	}
    }
    
    
    
    /*
     * Save processing
     */
    public void onClick_saveData(View v){
    	if(isDataValid()){
    		runOperationAsync(OPERATION_SET_DATA, getString(R.string.progress_saving), false);
    	} else {
    		showOperationError(R.string.msg_title_invalid_data, formErrorString);
    	}
    }//onClick_saveData
    
    
    
    /*
     * Check form data
     */
    private boolean isDataValid(){
    	
    	boolean result = true;
    	
    	String[] categoryArray =  getResources().getStringArray(R.array.arr_conversionCategory_api);
    	
    	category = categoryArray[spin_conversion_category.getSelectedItemPosition()];
    	
    	markupLanguage = spin_conversion_markup_language.getItemAtPosition(spin_conversion_markup_language.getSelectedItemPosition()).toString();
    	httpProtocol = spin_conversion_page_security.getItemAtPosition(spin_conversion_page_security.getSelectedItemPosition()).toString();
    	
    	if(rb_conversion_notif_line1.isChecked() && rb_conversion_add_notif.isChecked()){
    		textFormat = "ONE_LINE";
    	} else if(rb_conversion_notif_line2.isChecked() && rb_conversion_add_notif.isChecked()){
    		textFormat = "TWO_LINE";
    	} else if(rb_conversion_no_notif.isChecked()){
    		textFormat = "HIDDEN";
    	}
    	
    	conversionPageLanguage = ((Language)spin_conversion_notif_language.getItemAtPosition(spin_conversion_notif_language.getSelectedItemPosition())).getCode();
    	
    	userRevenueValue = edit_conversion_revenue_value.getText().toString();
    	
    	if(!DataValidator.isAmount(userRevenueValue, true)){
    		formErrorString = getString(R.string.msg_invalid_conversion_value);
    		result = false;
    	}
    	
    	backgroundColor = edit_conversion_notif_bg_color.getText().toString();
    	
		return result;
    }//isDataValid
    
    
    
    /*
     * Async operation
     */
	private void runOperationAsync(final int operation, String message, boolean overlap) {
		// Stop if thread is alive
		if (thread.isAlive() && !overlap)
			return;

		// Show progress dialog
		final ProgressDialog progressDialog = ProgressDialog.show(this, "",
				message, true);

		// Check if Internet connection alive
		if (!isConnectionAvalable()) {
			progressDialog.dismiss();
			return;
		}

		thread = new Thread() {
			public void run() {
				// Perform authentication
				new AuthService(Act_ConversionSettings.this, getApplication());

				// Perform operation
				if (AuthService.authToken != null) {
					try {
						switch (operation) {
						case OPERATION_SET_DATA:
							Act_ConversionSettings.this.conversionSetOperation();
							break;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				// Perform postoperation
				Act_ConversionSettings.this.runOnUiThread(new Runnable() {
					public void run() {

						progressDialog.dismiss();

						if (AuthService.authToken != null) {

							showOperationError(R.string.msg_title_error,
									responseErrorString);

							switch (operation) {
							case OPERATION_SET_DATA:
								if (responseErrorString == null)
									finishActivityWithResult(RESPONSE_REFRESH_REQUIRED);
								break;
							}

						} else {
							Intent intent = new Intent(Act_ConversionSettings.this
									.getApplicationContext(), Act_Login.class);
							startActivityForResult(intent,
									REQUEST_REFRESH_REQUIRED);
						}
					}
				});
			}
		};
		thread.start();

	}//runOperationAsync


	protected void conversionSetOperation() {
		String resp = Communication.postSOAP(
				ConversionService.URL_CONVERSION_SERVICE, 
				ConversionService.conversionSetSettings(conversionId, category, 
    					markupLanguage, httpProtocol, textFormat, conversionPageLanguage, 
    					backgroundColor, userRevenueValue)
    		);

    	ConversionResponseParser parser = new ConversionResponseParser(resp);
    	responseErrorString = parser.checkForErrors();
	}
	
}
